<template>
  <div class="add-course-container">

    <!-- 主内容区 -->
    <main class="main-content">
      <div class="add-course-wrapper">
        <h2 class="page-title">添加课程</h2>
        
        <!-- 添加课程表单 -->
        <el-form ref="courseForm" :model="courseForm" :rules="courseRules" label-width="120px" class="course-form">
          <!-- 课程基本信息 -->
          <el-form-item label="课程名称" prop="title">
            <el-input v-model="courseForm.title" placeholder="请输入课程名称" maxlength="50"></el-input>
          </el-form-item>
          
          <el-form-item label="课程类别" prop="categoryid">
            <el-select v-model="courseForm.categoryid" placeholder="请选择课程类别">
              <el-option v-for="category in categories" :key="category.id" :label="category.title" :value="category.id"></el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item label="课程教师" prop="teacher">
            <el-input v-model="courseForm.teacher" placeholder="请输入课程教师姓名" maxlength="20"></el-input>
          </el-form-item>
          
          <el-form-item label="上课时间" prop="courseTime">
            <el-date-picker
              v-model="courseForm.courseTime"
              type="datetime"
              placeholder="选择日期时间"
              format="YYYY-MM-DD HH:mm"
              value-format="YYYY-MM-DD HH:mm"
              :picker-options="{}"
              style="width: 100%;"
            ></el-date-picker>
          </el-form-item>
          
          <el-form-item label="课程简介" prop="description">
            <el-input v-model="courseForm.description" type="textarea" placeholder="请输入课程简介" :rows="4" maxlength="500"></el-input>
          </el-form-item>
          
          <el-form-item label="课程封面图" prop="coverImage">
            <el-upload
              class="avatar-uploader"
              :show-file-list="true"
              :auto-upload="true"
              :on-success="handleImageUpload"
              :before-upload="beforeImageUpload"
              :action="uploadUrl"
              :headers="{ 'Authorization': `Bearer ${token}` }"
            >
              <img v-if="courseForm.coverImage" :src="courseForm.coverImage" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          
          <!-- 提交按钮 -->
          <el-form-item>
            <el-button type="primary" @click="handleAddCourse" :loading="loading">添加课程</el-button>
            <el-button @click="handleCancel">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </main>

    <!-- 页脚 -->
    <footer class="footer">
      <p>© 2025 课程学习网站 | 数字化成长空间</p>
    </footer>
  </div>
</template>

<script>
import { courseAPI, categoryAPI } from '../api'
import { ElMessage } from 'element-plus'

export default {
  name: 'AddCourseView',
  data() {
    return {
      activeIndex: 'add-course',
      courseForm: {
        title: '',
        categoryid: '',
        teacher: '',
        courseTime: '', // 使用空字符串作为初始值，与yyyy-MM-dd HH:mm格式匹配
        description: '',
        coverImage: ''
      },
      courseRules: {
        title: [
          { required: true, message: '请输入课程名称', trigger: 'blur' },
          { min: 2, max: 50, message: '课程名称长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        categoryid: [
          { required: true, message: '请选择课程类别', trigger: 'change' }
        ],
        teacher: [
          { required: true, message: '请输入课程教师姓名', trigger: 'blur' },
          { min: 2, max: 20, message: '教师姓名长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        courseTime: [
          { required: true, message: '请选择上课时间', trigger: 'change' }
        ],
        description: [
          { required: true, message: '请输入课程简介', trigger: 'blur' },
          { min: 10, max: 500, message: '课程简介长度在 10 到 500 个字符', trigger: 'blur' }
        ]
      },
      categories: [],
      loading: false,
      token: '',
      uploadUrl: '/api/demo/upload' // 统一使用相对路径，由axios实例处理baseURL
    }
  },
  computed: {
    userInfo() {
      const userInfoStr = localStorage.getItem('userInfo')
      return userInfoStr ? JSON.parse(userInfoStr) : null
    }
  },
  async mounted() {
    // 获取用户信息
    this.token = localStorage.getItem('token')
    
    // 检查登录状态
    if (!this.token || !this.userInfo) {
      ElMessage.warning('请先登录')
      this.$router.push('/login')
      return
    }
    
    // 加载课程类别
    await this.loadCategories()
  },
  methods: {
    async loadCategories() {
      try {
        const response = await categoryAPI.getAllCategories('课程')
        this.categories = response || []
        
        if (this.categories.length === 0) {
          ElMessage.info('暂无课程类别，请先添加课程类别')
        }
      } catch (error) {
        console.error('加载类别错误:', error)
        // 使用自定义错误信息或默认错误信息
        ElMessage.error(error.customMessage || '加载课程类别失败，请稍后重试')
      }
    },
    async handleAddCourse() {
      try {
        this.$refs.courseForm.validate(async (valid) => {
          if (valid) {
            this.loading = true
            
            // 准备课程数据，确保字段名称与后端API要求相匹配
              // 直接使用字符串格式的日期时间
              if (!this.courseForm.courseTime) {
                ElMessage.error('请选择有效的上课时间');
                this.loading = false;
                return;
              }
              
              // 转换为Date对象
              const courseDate = new Date(this.courseForm.courseTime);
              
              // 验证日期是否有效
              if (isNaN(courseDate.getTime())) {
                ElMessage.error('请选择有效的上课时间');
                this.loading = false;
                return;
              }
              
              // 格式化日期为MySQL可接受的格式 (YYYY-MM-DD HH:MM:SS)
              const formattedStartTime = `${courseDate.getFullYear()}-${String(courseDate.getMonth() + 1).padStart(2, '0')}-${String(courseDate.getDate()).padStart(2, '0')} ${String(courseDate.getHours()).padStart(2, '0')}:${String(courseDate.getMinutes()).padStart(2, '0')}:${String(courseDate.getSeconds()).padStart(2, '0')}`;
              
              const courseData = {
                title: this.courseForm.title,
                body: this.courseForm.description, // 后端需要body字段
                categoryid: this.courseForm.categoryid,
                teachername: this.courseForm.teacher, // 后端使用teachername字段
                startTime: formattedStartTime, // 使用MySQL可接受的日期格式
                coverImage: this.courseForm.coverImage,
                userid: this.userInfo.id, // 后端需要userid字段
                createTime: Date.now()
              }
            
            // 调用API添加课程
            const result = await courseAPI.addCourse(courseData)
            
            // 正确检查API返回的结果，确保它是一个对象且errno为0
            if (result && typeof result === 'object') {
              if (result.errno === 0 && result.data) {
                ElMessage.success('课程添加成功')
                
                // 添加成功后，提示用户可以添加课程任务项
                this.$confirm('课程添加成功，是否继续添加课程任务项？', '提示', {
                  confirmButtonText: '继续',
                  cancelButtonText: '返回首页',
                  type: 'success'
                }).then(() => {
                  // 跳转到添加课程任务项页面，并传递课程ID
                  this.$router.push(`/add-subitem/${result.data.id}`)
                }).catch(() => {
                  // 返回首页
                  this.$router.push('/')
                })
              } else {
                // 如果有错误信息，显示错误信息
                const errorMessage = result.message || '课程添加失败'
                ElMessage.error(errorMessage)
              }
            } else {
              ElMessage.error('课程添加失败')
            }
          }
        })
      } catch (error) {
        console.error('添加课程错误:', error)
        // 使用自定义错误信息或默认错误信息
        ElMessage.error(error.customMessage || '添加课程失败，请稍后重试')
      } finally {
        this.loading = false
      }
    },
    // 图片上传前的校验
    beforeImageUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      
      if (!isJPG) {
        ElMessage.error('上传头像图片只能是 JPG/PNG 格式!')
      }
      if (!isLt2M) {
        ElMessage.error('上传头像图片大小不能超过 2MB!')
      }
      
      return isJPG && isLt2M
    },
    // 图片上传成功回调
    handleImageUpload(response, file, fileList) {
      if (response && response.url) {
        this.courseForm.coverImage = response.url
        ElMessage.success('图片上传成功')
      } else {
        ElMessage.error('图片上传失败')
      }
    },
    resetForm() {
      this.courseForm = {
        title: '',
        categoryid: '',
        teacher: '',
        courseTime: '',
        description: '',
        coverImage: ''
      }
      
      if (this.$refs.courseForm) {
        this.$refs.courseForm.resetFields()
      }
    },
    handleCancel() {
      this.resetForm()
      this.$router.push('/')
    }
  }
}
</script>

<style scoped>
.add-course-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}



/* 主内容区样式 */
.main-content {
  flex: 1;
  max-width: 1200px;
  width: 100%;
  margin: 20px auto;
  padding: 0 20px;
}

/* 添加课程包装 */
.add-course-wrapper {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 30px;
}

/* 页面标题 */
.page-title {
  font-size: 24px;
  color: #303133;
  margin-bottom: 30px;
  text-align: center;
}

/* 课程表单 */
.course-form {
  max-width: 800px;
  margin: 0 auto;
}

/* 图片上传样式 */
.avatar-uploader {
  display: flex;
  align-items: center;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
  border-radius: 4px;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  background-color: #f5f7fa;
  cursor: pointer;
  transition: border-color 0.3s;
}

.avatar-uploader-icon:hover {
  border-color: #409eff;
}

/* 页脚 */
.footer {
  background-color: #fff;
  padding: 20px 0;
  text-align: center;
  border-top: 1px solid #e6e6e6;
  margin-top: auto;
}

.footer p {
  color: #909399;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .add-course-wrapper {
    padding: 20px;
  }
  
  .page-title {
    font-size: 20px;
  }
  
  .course-form {
    max-width: 100%;
  }
  
  .el-form {
    --el-form-label-width: 100px !important;
  }
  
  .avatar,
  .avatar-uploader-icon {
    width: 100px;
    height: 100px;
    line-height: 100px;
  }
}
</style>